'use strict';
const http = require('http');
const Koa = require('koa');
const app = new Koa();
const httpServer = http.createServer(app.callback());
const Router = require('koa-router');
const router = new Router();
const io = require('socket.io')(httpServer);
const fs = require('fs');
const path = require('path');

router.get('/', async (ctx, next) => {
    const text = await new Promise(rs => {
        fs.readFile(path.join(__dirname, 'chat.html'), 'utf-8', function (err, text) {
            rs(text);
        });
    });
    ctx.body = text;
});

app.use(router.routes()).use(router.allowedMethods());

io.on('connection', function(socket){
    console.log('a user connected');
    socket.on('disconnect', function () {
        console.log('user disconnected');
    });

    socket.broadcast.emit('chat message', 'hi');

    socket.on('chat message', function(msg){
        console.log('message: ' + msg);
        io.emit('chat message', msg);
    });
});

httpServer.listen(3000, function(){
    console.log('listening on *:3000');
});
